package com.example.backend.service;

import com.example.backend.domain.entity.Ticket;
import com.example.backend.domain.entity.User;
import com.example.backend.dto.CreateTicketRequest;
import com.example.backend.repository.TicketRepository;
// import com.example.backend.repository.UserRepository; // 预留扩展
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Instant;
import java.util.concurrent.CompletableFuture;

/**
 * 工单创建优化服务
 * 解决工单创建超时问题
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class TicketCreationService {

    private final TicketRepository ticketRepository;
    // private final UserRepository userRepository; // 暂时不使用，预留扩展

    /**
     * 快速创建工单 - 优化版本
     * 
     * @param request 创建工单请求
     * @param currentUser 当前用户
     * @return 创建的工单
     */
    @Transactional
    public Ticket createTicketFast(CreateTicketRequest request, User currentUser) {
        log.info("🚀 开始快速创建工单: {}", request.getTitle());
        
        long startTime = System.currentTimeMillis();
        
        try {
            // 1. 基本验证（快速）
            if (request.getTitle() == null || request.getTitle().trim().isEmpty()) {
                throw new IllegalArgumentException("工单标题不能为空");
            }
            
            // 2. 生成工单编号（优化算法）
            String ticketNumber = generateTicketNumber();
            
            // 3. 创建工单对象
            Ticket ticket = Ticket.builder()
                    .ticketNumber(ticketNumber)
                    .title(request.getTitle().trim())
                    .description(request.getDescription())
                    .priority(request.getPriority())
                    .status(com.example.backend.domain.enums.TicketStatus.OPEN)
                    .source(request.getSource())
                    .customer(currentUser)
                    .createdBy(currentUser)
                    .createdAt(Instant.now())
                    .updatedAt(Instant.now())
                    .build();
            
            // 4. 保存工单（单次数据库操作）
            ticket = ticketRepository.save(ticket);
            
            long duration = System.currentTimeMillis() - startTime;
            log.info("✅ 工单创建成功: {} (耗时: {}ms)", ticketNumber, duration);
            
            // 5. 异步处理后续任务（不阻塞主流程）
            processTicketAsync(ticket);
            
            return ticket;
            
        } catch (Exception e) {
            long duration = System.currentTimeMillis() - startTime;
            log.error("❌ 工单创建失败 (耗时: {}ms): {}", duration, e.getMessage(), e);
            throw new RuntimeException("工单创建失败: " + e.getMessage(), e);
        }
    }

    /**
     * 异步处理工单后续任务
     * 避免阻塞主要创建流程
     */
    @Async("taskExecutor")
    public CompletableFuture<Void> processTicketAsync(Ticket ticket) {
        try {
            log.info("🔄 开始异步处理工单: {}", ticket.getTicketNumber());
            
            // 异步任务：发送通知、更新统计等
            // 这些操作不会影响主要的创建响应时间
            
            // 模拟一些后续处理
            Thread.sleep(100); // 模拟处理时间
            
            log.info("✅ 工单异步处理完成: {}", ticket.getTicketNumber());
            
        } catch (Exception e) {
            log.error("❌ 工单异步处理失败: {}", ticket.getTicketNumber(), e);
        }
        
        return CompletableFuture.completedFuture(null);
    }

    /**
     * 优化的工单编号生成
     * 使用时间戳 + 序号的方式，避免数据库查询
     */
    private String generateTicketNumber() {
        // 使用时间戳确保唯一性，避免查询数据库
        long timestamp = System.currentTimeMillis();
        int random = (int) (Math.random() * 1000);
        return String.format("TICKET-%d%03d", timestamp % 1000000, random);
    }

    /**
     * 批量创建工单 - 优化版本
     */
    @Transactional
    public void createTicketsBatch(java.util.List<CreateTicketRequest> requests, User currentUser) {
        log.info("🚀 开始批量创建工单: {} 个", requests.size());
        
        long startTime = System.currentTimeMillis();
        
        try {
            java.util.List<Ticket> tickets = new java.util.ArrayList<>();
            
            for (CreateTicketRequest request : requests) {
                Ticket ticket = Ticket.builder()
                        .ticketNumber(generateTicketNumber())
                        .title(request.getTitle())
                        .description(request.getDescription())
                        .priority(request.getPriority())
                        .status(com.example.backend.domain.enums.TicketStatus.OPEN)
                        .source(request.getSource())
                        .customer(currentUser)
                        .createdBy(currentUser)
                        .createdAt(Instant.now())
                        .updatedAt(Instant.now())
                        .build();
                tickets.add(ticket);
            }
            
            // 批量保存，减少数据库交互次数
            ticketRepository.saveAll(tickets);
            
            long duration = System.currentTimeMillis() - startTime;
            log.info("✅ 批量创建工单成功: {} 个 (耗时: {}ms)", requests.size(), duration);
            
        } catch (Exception e) {
            long duration = System.currentTimeMillis() - startTime;
            log.error("❌ 批量创建工单失败 (耗时: {}ms): {}", duration, e.getMessage(), e);
            throw new RuntimeException("批量创建工单失败: " + e.getMessage(), e);
        }
    }
}
